<template>
    <div>
        <el-divider content-position="left">您具有一定的操作权限</el-divider>
    </div>

    <div>
        <el-divider>
            <span id="spanlittlepart">查询</span>
        </el-divider>
    </div>

    <!-- 查询 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="生长习性" style="width: 250px;">
            <el-input v-model="checkformInline.habit" placeholder="habit"></el-input>
        </el-form-item>
        <el-form-item label="适宜地区" style="width: 180px;">
            <el-input v-model="checkformInline.suitable_area" placeholder="suitable_area"></el-input>
        </el-form-item>
        <el-form-item style="width: 150px;">
            <el-button @click="search" type="primary" plain style="width: 200px;">查询</el-button>
        </el-form-item>
    </el-form>

    <el-divider>
        <el-icon><star-filled /></el-icon>
    </el-divider>

    <el-button type="primary" plain :onclick="onAddItem" class="addbtn">
        <el-icon>
            <Edit />
        </el-icon>
        <span> 创建新的植株详情</span>
    </el-button>

    <!-- 展示表格 -->
    <el-table :data="tableData" style="width: 100%; margin: 0 auto;  ">
        <el-table-column prop="category" label="分类" sortable width="100" column-key="date" :filters="[
            { text: '水果', value: '水果' },
            { text: '蔬菜', value: '蔬菜' },
            { text: '鲜花', value: '鲜花' },
        ]" :filter-method="filterHandler" />
        <el-table-column prop="habit" label="生长习性" width="400" />
        <el-table-column prop="suitable_area" label="适宜地区" width="120" />
        <el-table-column prop="cropname" label="植物名" width="" />
        <el-table-column label="植株图片" width="120">
            <template #default="scope">
                <div style="display: flex; align-items: center">
                    <el-image :src="baseURL + tableData[scope.$index].cropimg"
                        :preview-src-list="[baseURL + tableData[scope.$index].cropimg]" :preview-teleported="true"
                        :initial-index="scope.$index" :fit="contain"
                        style="width: 100px; height: 100px; padding-left: -30px;margin-left: -30px; overflow: visible; " />
                </div>
            </template>
        </el-table-column>
        <el-table-column prop="maxtemp" label="适宜生长的最高温度" width="90" />
        <el-table-column prop="mintemp" label="适宜生长的最低温度" width="90" />
        <el-table-column prop="wettemp" label="适宜湿度" width="100" />
        <el-table-column prop="ifsun" label="是否喜光" width="100" />
        <el-table-column fixed="right" label="操作" width="100" style="text-align: left;">
            <template #default="scope">
                <el-button link type="primary" size="small" style="margin-left: 0;"
                    @click.prevent="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button link type="primary" size="small" style="margin-left: 0;"
                    @click.prevent="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- Form -->
    <el-dialog v-model="dialogFormVisible" title="编辑" :destroy-on-close="true">
        <el-form :model="form">
            <el-form-item label="分类" :label-width="formLabelWidth">
                <el-select v-model="form.category" placeholder="请选择水果/蔬菜/鲜花">
                    <el-option label="水果" value="水果" />
                    <el-option label="蔬菜" value="蔬菜" />
                    <el-option label="鲜花" value="鲜花" />
                </el-select>
            </el-form-item>
            <el-form-item label="生长习性" :label-width="formLabelWidth">
                <el-input v-model="form.habit" autocomplete="off" type="textarea" :rows="2" />
            </el-form-item>
            <el-form-item label="适宜地区" :label-width="formLabelWidth">
                <el-input v-model="form.suitable_area" autocomplete="off" />
            </el-form-item>
            <el-form-item label="植物名" :label-width="formLabelWidth">
                <el-input v-model="form.cropname" autocomplete="off" />
            </el-form-item>
            <el-form-item label="适宜生长的最高温度" :label-width="formLabelWidth">
                <el-input v-model="form.maxtemp" autocomplete="off" />
            </el-form-item>
            <el-form-item label="适宜生长的最低温度" :label-width="formLabelWidth">
                <el-input v-model="form.mintemp" autocomplete="off" />
            </el-form-item>
        </el-form>
        <el-form-item label="适宜生长湿度" :label-width="formLabelWidth" style="margin-bottom: 30px;">
            <el-slider v-model="wet" range :marks="marks">
            </el-slider>
        </el-form-item>
        <el-form-item label="是否喜光" :label-width="formLabelWidth">
            <el-input v-model="form.ifsun" autocomplete="off" />
        </el-form-item>
        <span class="spantext">添加植株图片:</span>
        <el-upload v-model:file-list="editfileList" class="upload-demo" action="#" :on-preview="handlePreview"
            :auto-upload="false" :before-upload="handleChange" :on-remove="handleRemove" list-type="picture"
            :multiple="false" :limit="1">
            <el-button type="primary">点击进行商品详情图片上传</el-button>
            <template #tip>
                <div class="el-upload__tip">
                    只能上传上传1张图片文件，图片大小不得超过5MB
                </div>
            </template>
        </el-upload>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="onSaveInfo">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>

    <el-pagination background layout="prev, pager, next" :current-page="page" @update:current-page="handleCurrentChange"
        :total="total" :page-size="size" style="bottom: 0; text-align: center;margin-left: 45%;margin-top: 5px;" />

    <!-- Form -->
    <el-dialog v-model="dialogaddFormVisible" title="添加Tags" :destroy-on-close="true">
        <el-form :model="addform">
            <el-form-item label="分类" :label-width="formLabelWidth">
                <el-select v-model="addform.category" placeholder="请选择水果/蔬菜/鲜花">
                    <el-option label="水果" value="水果" />
                    <el-option label="蔬菜" value="蔬菜" />
                    <el-option label="鲜花" value="鲜花" />
                </el-select>
            </el-form-item>
            <el-form-item label="生长习性" :label-width="formLabelWidth">
                <el-input v-model="addform.habit" autocomplete="off" />
            </el-form-item>
            <el-form-item label="适宜地区" :label-width="formLabelWidth">
                <el-input v-model="addform.suitable_area" autocomplete="off" />
            </el-form-item>
            <el-form-item label="植物名" :label-width="formLabelWidth">
                <el-input v-model="addform.cropname" autocomplete="off" />
            </el-form-item>
            <el-form-item label="适宜生长的最高温度" :label-width="formLabelWidth">
                <el-input v-model="addform.maxtemp" autocomplete="off" />
            </el-form-item>
            <el-form-item label="适宜生长的最低温度" :label-width="formLabelWidth">
                <el-input v-model="addform.mintemp" autocomplete="off" />
            </el-form-item>
            <el-form-item label="适宜生长湿度" :label-width="formLabelWidth" style="margin-bottom: 30px;">
                <el-slider v-model="value" range :marks="marks">
                </el-slider>
            </el-form-item>
            <el-form-item label="是否喜光" :label-width="formLabelWidth" style="margin-top: 10px;">
                <el-input v-model="addform.ifsun" autocomplete="off" />
            </el-form-item>
            <span class="spantext">添加植株图片:</span>
            <el-upload v-model:file-list="fileList" class="upload-demo" action="#" :on-preview="handlePreview"
                :auto-upload="false" :before-upload="handleChange" :on-remove="handleRemove" list-type="picture"
                :multiple="false" :limit="1">
                <el-button type="primary">点击进行商品详情图片上传</el-button>
                <template #tip>
                    <div class="el-upload__tip">
                        只能上传上传1张图片文件，图片大小不得超过5MB
                    </div>
                </template>
            </el-upload>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeadd">取消</el-button>
                <el-button type="primary" @click="onAddInfo">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
    <!-- </div> -->
</template>
<script setup>
import {
    Guide,
    PictureFilled,
    User,
    HomeFilled,
    ChatLineSquare,
    Apple,
    Document,
    List,
    Tools,
    ShoppingCart,
    CollectionTag,
    Finished,
    InfoFilled,
    Cherry,
    Goods,
    Sell,
    ShoppingCartFull,
    Van,
    Sunrise,
    StarFilled,
    EditPen,
    Edit,
    Promotion,
    Grape,
    Pear,
} from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
const formLabelWidth = '140px';
</script>
<script>

export default {
    setup() {

    },
    data() {
        return {
            value: [25, 50],
            marks: {
                0: '0%',
                25: '25%',
                50: '50%',
                75: '75%',
                100: '100%'
            },
            baseURL: 'http://localhost:8080',
            fileList: [],
            fileArray: [],
            editfileArray: [],
            editfileList: [],
            categoryChosen: '水果/蔬菜/鲜花',
            categoryOptions: [
                {
                    value: '水果/蔬菜/鲜花',
                    label: '水果/蔬菜/鲜花',
                },
                {
                    value: '水果',
                    label: '水果',
                },
                {
                    value: '蔬菜',
                    label: '蔬菜',
                },
                {
                    value: '鲜花',
                    label: '鲜花',
                },
            ],
            formInline: {
                cropsid: 0,
                habit: '',
                suitable_area: '',
                cropimg: '',
                cropname: '',
                maxtemp: '',
                mintemp: '',
                category: '水果/蔬菜/鲜花',
                stateday: '',
                croptype: 0,
                wettemp: '',
                ifsun: ''
            },
            checkformInline: {
                cropsid: 0,
                habit: '',
                suitable_area: '',
                cropimg: '',
                cropname: '',
                maxtemp: '',
                mintemp: '',
                category: '水果/蔬菜/鲜花',
                stateday: '',
                croptype: '',
                wettemp: '',
                ifsun: ''
            },
            dialogFormVisible: false,
            dialogaddFormVisible: false,
            showSearch: false,
            tableData: [],
            tableDataStore: [],
            tableimgList: [],
            tableimg: '',
            tags: {
                cropsid: 0,
                habit: '',
                suitable_area: '',
                cropimg: '',
                cropname: '',
                maxtemp: '',
                mintemp: '',
                category: '水果/蔬菜/鲜花',
                stateday: '',
                croptype: 0,
                wettemp: '',
                ifsun: ''
            },
            form: {
                cropsid: 0,
                habit: '',
                suitable_area: '',
                cropimg: '',
                cropname: '',
                maxtemp: '',
                mintemp: '',
                category: '水果/蔬菜/鲜花',
                stateday: '',
                croptype: 0,
                wettemp: '',
                ifsun: ''
            },
            addform: {
                cropsid: 0,
                habit: '',
                suitable_area: '',
                cropimg: '',
                cropname: '',
                maxtemp: '',
                mintemp: '',
                category: '水果/蔬菜/鲜花',
                stateday: '',
                croptype: 0,
                wettemp: '',
                ifsun: ''
            },
            searchForm: [],
            filetype: [
                "jpg",
                "jpeg",
                "png",
            ],
            categoryChange: 9,
            wet: [],
            addcategoryChange: 9,
            weatherChange: 9,
            placeChange: 9,
            page: 1, // 当前页码
            total: 0, // 总条数
            size: 10, // 每页的数据条数
            reallyTable: [],
            selData: [],
        }

    },
    methods: {
        init() {
            axios({
                method: 'post',
                url: 'http://localhost:8080/tags/gettagsbackend',
                withCredentials: true,
            }).then(res => {
                this.tableData = res.data.data;
                this.tableDataStore = res.data.data;
                console.log(res.data.data);
                this.tableData = res.data.data.slice(
                    (this.page - 1) * this.size,
                    this.page * this.size
                );
                this.total = res.data.data.length;
                this.selData = res.data.data;
                for (var i = 0; i < res.data.data.length; i++) {
                    this.tableimgList.push(res.data.data[i].cropimg);
                    res.data.data[i].category == 1 ? this.tableDataStore[i].category = '水果' : (res.data.data[i].category == 2 ? this.tableDataStore[i].category = '蔬菜' : this.tableDataStore[i].category = '鲜花')
                    // this.getPlace(i);
                    this.tableDataStore[i].wettemp ? this.tableDataStore[i].wettemp = JSON.parse(res.data.data[i].wettemp)[0] + '%~' + JSON.parse(res.data.data[i].wettemp)[1] + '%' : ''

                }
                //console.log("tableimglist:" + this.tableimgList);
                this.tableimg = this.tableimgList[0];
                //console.log("tableimg：-------->" + this.tableimg);
            })
        },
        search() {
            let arr = []
            console.log(this.tableDataStore.length)
            for (let i = 0; i < this.tableDataStore.length; i++) {
                if (String(this.tableDataStore[i].habit).includes(this.checkformInline.habit) &&
                    String(this.tableDataStore[i].suitable_area).includes(this.checkformInline.suitable_area)) {
                    arr.push(this.tableDataStore[i])
                }
            }
            console.log(arr);
            this.tableData = arr.slice(
                (this.page - 1) * this.size,
                this.page * this.size
            );
            this.selData = arr;
            this.total = arr.length;
        },
        closeadd() {
            this.addform = {
                cropsid: 0,
                habit: '',
                suitable_area: '',
                cropimg: '',
                cropname: '',
                maxtemp: '',
                mintemp: '',
                category: '水果/蔬菜/鲜花',
                stateday: '',
                croptype: 0,
                wettemp: '',
                ifsun: ''
            },
            this.dialogaddFormVisible = false
        },
        filterHandler(
            value,
            row,
            column
        ) {
            console.log();
            const property = column['property']
            console.log(property);
            console.log(row[property]);
            console.log(value);
            console.log(this.tableDataStore);
            this.selData = this.tableDataStore.filter(function (item) {
                if (item.category == value) {
                    console.log(item);
                    return true;
                } else {
                    return false;
                }
            })
            this.tableData = this.selData.slice(
                (this.page - 1) * this.size,
                this.page * this.size
            );
            this.total = this.selData.length
            // return row[property] === value
        },
        handleRemove(file, fileList) {
            this.fileList = fileList
        },
        handlePreview(file) {
            console.log(file);
        },
        handleChange(file, fileList) {
            let isRightSize = file.size / 1024 / 1024 < 20
            if (!isRightSize) {
                this.$message.error('文件大小超过 20MB')
            }
            let fileName = file.name;
            let pos = fileName.lastIndexOf(".");
            let lastName = fileName.substring(pos, fileName.length);
            let isAccept = true;
            if (lastName.toLowerCase() !== ".jpg" && lastName.toLowerCase() !== ".png" && lastName.toLowerCase() !== ".jpeg") {
                this.$message.error("文件必须为.jpg,.png,.jpeg类型");
                isAccept = false;
                // 清空文件列表
                const newFileList = this.fileList.slice();
                newFileList.splice(0, 1);
                this.fileList = newFileList;
            }
        },
        //删除表格行
        handleDelete(index, row) {
            console.log(index, row);
            console.log(row.cropsid);//可以获取到
            ElMessageBox.confirm(
                '确认删除本项吗？删除后无法找回:-0',
                'Warning',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(() => {
                    axios({
                        method: 'post',
                        url: 'http://localhost:8080/tags/deltagsbackend',
                        withCredentials: true,
                        data: {
                            cropsid: row.cropsid,
                        },
                    }).then(res => {
                        // if (res.data.data.code == 200) {
                            this.init()
                            ElMessage({
                                type: 'success',
                                message: '删除成功',
                            })

                        // }

                    })
                })
                .catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '取消删除操作',
                    })
                })
        },
        //编辑表格行
        handleEdit(index, row) {
            console.log(index, row);
            this.dialogFormVisible = true;
            // for (let i = 0; i < row..length; i++) {
            console.log(row.cropimg);
            this.editfileList[0] = { name: 0, url: this.baseURL + row.cropimg }
            // }
            axios({
                method: 'post',
                url: 'http://localhost:8080/tags/getsinglebackend',
                withCredentials: true,
                data: {
                    cropsid: index + 1
                },
            }).then(res => {
                console.log(res.data.data)
                this.form = row;
                console.log(row.wettemp);
                let wet = row.wettemp.split('~')
                let wet1 = wet[0].split('%')[0]
                let wet2 = wet[1].split('%')[0]
                this.wet = [wet1, wet2]
                console.log(this.form);
            })
        },
        async onSaveInfo() {
            console.log(this.categoryChange)
            this.form.category == '水果' ? this.categoryChange = 1 : (this.form.category == '蔬菜' ? this.categoryChange = 2 : this.categoryChange = 3);
            console.log(this.categoryChange)
            console.log(this.editfileList);
            if (isNaN(this.form.maxtemp) || isNaN(this.form.mintemp)) {
                alert("适宜生长气温需为数字，请重新输入")
            } else if (this.form.maxtemp != '' && this.form.mintemp != '' && this.form.habit != '' && this.editfileList.length != 0 && this.form.category != '' && this.form.suitable_area != '' && this.ifsun != '') {

                const editfileArray = this.editfileList;
                console.log(this.editfileList);
                this.editfileArray = this.editfileList
                console.log(editfileArray);
                for (let i = editfileArray.length - 1; i >= 0; i--) {
                    if (editfileArray[i].status == 'ready') {
                        console.log(i);
                        let lastName = this.getLastName(editfileArray, i)
                        await this.getBase64(editfileArray[i].url).then(res => {
                            this.editfileArray[i].url = res
                            this.editfileArray[i].name = new Date().getTime() + Math.floor(Math.random() * (0 - 1000)) + 1000 + '.' + lastName
                        })
                    }
                }
                axios({
                    method: 'post',
                    url: 'http://localhost:8080/tags/uploadimg',
                    withCredentials: true,
                    data: {
                        cropsid: this.form.cropsid,
                        habit: this.form.habit,
                        suitable_area: this.form.suitable_area,
                        cropname: this.form.cropname,
                        maxtemp: parseFloat(this.form.maxtemp),
                        mintemp: parseFloat(this.form.mintemp),
                        category: parseFloat(this.addcategoryChange),
                        stateday: this.form.stateday,
                        cropimg: this.editfileArray,
                        wettemp: JSON.stringify(this.wet),
                        ifsun: this.form.ifsun
                    },
                }).then(res => {
                    console.log(res);
                    this.init()
                })
            } else {
                alert("存在未输入项，请检查")
            }
            this.dialogFormVisible = false;
        },
        //增添项
        onAddItem() {
            this.dialogaddFormVisible = true;
            console.log('additem');
        },
        getLastName(fileArray, i) {
            let pos = fileArray[i].name.lastIndexOf(".");
            let lastName = fileArray[i].name.substring(pos + 1, fileArray[i].name.length);
            return lastName
        },
        getBase64(imgUrl) {
            return new Promise((resolve, reject) => {
                if (!imgUrl) {
                    reject('请传入imgUrl内容')
                }
                window.URL = window.URL || window.webkitURL
                var xhr = new XMLHttpRequest()
                xhr.open('get', imgUrl, true)
                xhr.responseType = 'blob'
                xhr.onload = function () {
                    if (this.status == 200) {
                        // 得到一个blob对象
                        var blob = this.response
                        const oFileReader = new FileReader()
                        oFileReader.onloadend = function (e) {
                            const base64 = e.target.result
                            resolve(base64 || '')
                        }
                        oFileReader.readAsDataURL(blob)
                    }
                }
                xhr.send()

            })
        },
        async onAddInfo() {
            this.addform.category == '水果' ? this.addcategoryChange = 1 : (this.addform.category == '蔬菜' ? this.addcategoryChange = 2 : this.addcategoryChange = 3);
            console.log(this.addcategoryChange)
            //上传图片到数据库
            // var file = document.querySelector("#add").files[0];
            if (isNaN(this.addform.maxtemp) || isNaN(this.addform.mintemp)) {
                alert("适宜生长气温需为数字，请重新输入")
            } else if (this.addform.maxtemp != '' && this.addform.mintemp != '' && this.addform.habit != '' && this.addform.cropname != '' && this.addform.category != '' && this.addform.suitable_area != '' && this.fileList.length != 0) {
                const fileArray = this.fileList;
                console.log(this.fileList);
                this.fileArray = fileArray
                for (let i = fileArray.length - 1; i >= 0; i--) {
                    let lastName = this.getLastName(fileArray, i)
                    await this.getBase64(fileArray[i].url).then(res => {
                        this.fileArray[i].url = res
                        this.fileArray[i].name = new Date().getTime() + Math.floor(Math.random() * (0 - 1000)) + 1000 + '.' + lastName
                    })
                }
                axios({
                    method: 'post',
                    url: 'http://localhost:8080/tags/addtagsbackend',
                    withCredentials: true,
                    data: {
                        habit: this.addform.habit,
                        suitable_area: this.addform.suitable_area,
                        cropname: this.addform.cropname,
                        maxtemp: parseFloat(this.addform.maxtemp),
                        mintemp: parseFloat(this.addform.mintemp),
                        category: parseFloat(this.addcategoryChange),
                        stateday: this.addform.stateday,
                        cropimg: this.fileArray,
                        wettemp: JSON.stringify(this.value),
                        ifsun: this.addform.ifsun
                    },
                }).then(res => {
                    this.init()
                    console.log("additem");
                })
                console.log(this.fileArray);
            } else {
                alert("存在未输入项，请检查")
            }

            this.dialogaddFormVisible = false;
        },
        getPlace(index) {
            return this.tableData[index].category == 1 ? this.tableData[index].category = '水果' : (this.tableData[index].category == 2 ? this.tableData[index].category = '蔬菜' : this.tableData[index].category = '鲜花')
        },
        async handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.page = val
            this.tableData = this.selData.slice(
                (this.page - 1) * this.size,
                this.page * this.size
            );
            // this.currentPage = val;
            const data = { 'page': val }
            // await this.onload(data)
        },
    },
    mounted() {
        //页面加载完成后，将数据库内的内容赋给定义的data变量
        this.init()
    }
}
</script>
<style scoped>
#sidepart {
    width: 100%;
    position: absolute;
    top: 5px;
    font-family: '华文中宋';
}

#mainpart {
    width: 80%;
    position: absolute;
    top: 20px;
    left: 260px;
    font-family: '华文中宋';
}

#spanpart {
    font-size: 30px;
    font-family: '华文中宋';
}

/* dialog */
.el-button--text {
    margin-right: 15px;
}

.el-select {
    width: 300px;
}

.el-input {
    width: 300px;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}

#spanlittlepart {
    font-size: 15px;
    color: cadetblue;
    font-family: '华文中宋';
}

.spantext {
    margin-right: 20px;
}

.addbtn {
    width: 80%;
    margin-bottom: 20px;
    font-family: '华文中宋';
    position: relative;
    left: -50px;
}
</style>